package reportService

import (
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelAPI"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Reflect"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

func PopAll() ([]*commRedisRpc.ChannelRespondVO, error) {
	mutex.Lock()
	defer mutex.Unlock()

	respondVOList := make([]*commRedisRpc.ChannelRespondVO, 0)
	for serviceKey, list := range channelMap {
		channelEntity := commRedisService.FindEntity(edgeEntity.Type.ChannelEntity.Type(), func(entity commEntity.IEntity) bool {
			channelEntity := entity.(*edgeEntity.ChannelEntity)

			if channelEntity.ChannelType != commEnv.Service.ModelName {
				return false
			}
			if serviceKey != channelEntity.ChannelParam["serviceKey"] {
				return false
			}

			return true
		})

		if channelEntity == nil {
			delete(channelMap, serviceKey)
			continue
		}

		for _, pdu := range *list {
			respondVO := commRedisRpc.Type.ChannelRespondVO.New()
			respondVO.Type = commEnv.Service.ModelName
			respondVO.Name = channelEntity.(*edgeEntity.ChannelEntity).ChannelName

			if Reflect.IsString(pdu) {
				respondVO.Recv = pdu
			} else {
				respondVO.Recv = Hex.EncodeToString(pdu.([]byte))
			}

			respondVOList = append(respondVOList, respondVO)

			// 打印日志
			channelLogger.PrintChannelDebugLogger(respondVO.Name, "接收", respondVO.Recv)
		}
		delete(channelMap, serviceKey)
	}

	return respondVOList, nil
}

func Push(serviceKey string, data interface{}) {
	mutex.Lock()
	defer mutex.Unlock()

	list := channelMap[serviceKey]
	if list == nil {
		arr := make([]interface{}, 0)
		list = &arr
		channelMap[serviceKey] = list
	}

	*list = append(*list, data)

	// 向API框架发出信号：有数据需要上报了，调用PopAll()吧
	channelAPI.Service.NotifyReport()
}
